package com.jzy.common.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.zaxxer.hikari.HikariDataSource;


@Configuration
@MapperScan(basePackages = "com.jzy.dao", sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {

	/**
	 * 
	 * 方法描述 : 配置第一个数据源
	 * 创建者：jzy 
	 * 项目名称： ssm
	 * 类名： FirstTransactionManager.java
	 * 创建时间： 2018年12月27日 下午5:07:13
	 * Email：jzy19890914@gmail.com
	 * @return DataSource
	 */
	@Primary //不是必须
	@Bean
    public DataSource dataSource(){
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }
	
	@Bean(name = "sqlSessionFactory") 
	public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception { 
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 
		bean.setDataSource(dataSource); 
		//加载其他文件，如mapper.xml 
		// bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); 
		return bean.getObject();
	}
	
	@Bean(name = "transactionManager") 
	public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) { 
		return new DataSourceTransactionManager(dataSource); 
	}
	
	@Bean(name = "sqlSessionTemplate") 
	public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { 
		return new SqlSessionTemplate(sqlSessionFactory); 
	}

	
	
}
